package net.qiqb.core.executing.definition;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class CommandDefineRegistrar {


    private final Map<String, CommandDefine> commandDefinitionCache = new ConcurrentHashMap<>();


    public void registerCommandDefinition(CommandDefine commandDefinition) {
        String commandName = commandDefinition.getName();
        if (containsCommandDefinition(commandName)) {
            log.error("命令名称 {} 已存在。存在的命令定义为：{}", commandName, getCommandDefinition(commandName));
            throw new IllegalStateException("命令定义名称已经存在");
        }
        commandDefinitionCache.put(commandName, commandDefinition);
    }


    public void removeCommandDefinition(String commandName) {
        commandDefinitionCache.remove(commandName);
    }


    public CommandDefine getCommandDefinition(String commandName) {

        final CommandDefine commandDefinition = commandDefinitionCache.get(commandName);
        if (commandDefinition == null) {
            log.info("命令 {} 找不到定义", commandName);
            throw new IllegalStateException("找不到命令定义");
        }
        return commandDefinition;
    }

    public CommandDefine getCommandDefinition(Class<?> commandType) {
        CommandDefine commandDefinition = null;
        for (CommandDefine value : this.commandDefinitionCache.values()) {
            if (commandDefinition != null) {
                log.error("根据类型不能确定命令类型.命令类型：{}", commandType.getName());
                throw new IllegalStateException("命令类型对应多个命令定义");
            }
            commandDefinition = value;
        }
        if (commandDefinition == null) {
            throw new IllegalStateException("找不到命令定义");
        }
        return commandDefinition;
    }


    public boolean containsCommandDefinition(String commandName) {
        return commandDefinitionCache.containsKey(commandName);
    }

    public String[] getCommandDefinitionNames() {
        return commandDefinitionCache.keySet().toArray(new String[getCommandDefinitionCount()]);
    }

   /* public CommandConfig[] getCommandDefinitions() {
        return commandDefinitionCache.values().toArray(new CommandConfig[0]);
    }*/

    public int getCommandDefinitionCount() {
        return commandDefinitionCache.size();
    }

}
